import React, { useEffect, useState } from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Table,
    TableProps,
    Tooltip,
} from 'antd';
import renderIcons from "@/components/CustomIconSelector/conponents";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import EditDictData from "../DictionaryData/EditDictData";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { delType, getType, listType, refreshCache } from "@/clientApi/system/dict/type";
import { globalMessage } from "@/utils/message";
import { delData, listData } from "@/clientApi/system/dict/data";
import { useParams } from "next/navigation";
import RenderIconsCustom from "@/components/CustomIconSelector/conponents";
import { useConfirmModal } from "@/utils/ConfirmModal";

const DictView: React.FC = () => {
        const { confirm } = useConfirmModal();
    // 引入对应的路由参数
    const { dictId } = useParams() as { dictId: string};
    const initialQueryParams = {

        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        dictLabel: undefined,
        status: undefined,

    };

    interface DataType {
    }

    const [form] = Form.useForm();
    const [dataList, setDataList] = useState<DataType[]>([]);
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '字典编号',
            dataIndex: 'dictCode',
            key: 'dictCode',
            width: '200',
            align: 'center',
        },
        {
            title: '字典标签',
            dataIndex: 'dictLabel',
            key: 'dictLabel',
            align: 'center',
        },
        {
            title: '字典键值',
            dataIndex: 'dictValue',
            key: 'dictValue',
            align: 'center',
        }, {
            title: '字典排序',
            dataIndex: 'dictSort',
            key: 'dictSort',
            align: 'center',
        }, {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (_, record: any) => (
                <Space size="middle">
                    {record.status === "0" ? '正常' : "停用"}
                </Space>)
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            render: (_, record: any) => (
                <Space size="middle">
                    {record?.userId !== 1 && (
                        <Tooltip title="修改">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="edit"/>}
                                onClick={() => EditClick(record)} />
                        </Tooltip>

                    )}
                    {record?.userId !== 1 && (
                        <Tooltip title="删除">
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined />}
                                onClick={() => handleDelete(record)} />
                        </Tooltip>
                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState('');
    const [open, setOpen] = useState<boolean>(false);
    const [dictCode, setDictCode] = useState<string|undefined>(undefined);
    useEffect(() => {
        getTypeDetail();
    }, [dictId]);  // 监听 queryParams 变化，调用 getList
    useEffect(() => {

        getList()
    }, [queryParams]);
    const getTypeDetail = () => {
        getType(dictId).then((res: any) => {
            if (res.code == 200) {
                form.setFieldsValue({
                    dictType: res.data.dictType,
                });
                handleSearch()
            }

        });
    }
    /** 查询用户列表 */
    const getList = () => {
        if (!queryParams.dictType) return; // 避免无效请求
        listData(queryParams).then((res: any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                key: item.dictCode // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    const handleSearch = () => {
        form.validateFields().then(values => {
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                status: values.status,
                dictType: values.dictType,
                dictLabel: values.dictLabel,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        const currentDictType = form.getFieldValue('dictType'); // 保留当前 dictType
        console.log(currentDictType)
        form.setFieldsValue({
            dictType:currentDictType,
            dictLabel:undefined,
            status:undefined
        })
        setQueryParams({
            ...initialQueryParams,
            dictType: currentDictType // 保持 dictType 不变
        }); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 修改按钮
    const EditClick = (e: any) => {
        setDictCode(e.dictCode)
        setTitle("修改用户")
        setOpen(true)
    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const dictCodes = e.dictCode;
        confirm({
            title: '系统提示',
            content: (`是否确认删除字典编号为"${dictCodes}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                delData(dictCodes).then((res: any) => {
                    if (res?.code === 200) {
                         globalMessage().info("删除成功")
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }
    // 刷新缓存
    const handleRefreshCache = () => {
        refreshCache().then((res: any) => {
            globalMessage().success(res.msg)
        });
    }



    return (
        <div className='home'>
            <Row gutter={20} style={{ paddingTop: "20px" }}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        name="customized_form_controls"
                        style={{ marginTop: 10, marginLeft: 10, marginBottom: 10 }}
                        layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="dictType"
                            label="字典名称">
                            <Input  disabled/>
                        </Form.Item>
                        <Form.Item
                            name="dictLabel"
                            label="字典标签">
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="状态">
                            <Select
                                style={{
                                    width: 120,
                                }}

                                allowClear
                                options={[
                                    {
                                        value: 0,
                                        label: '正常',
                                    }, {
                                        value: 1,
                                        label: '停用',
                                    },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary"  onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div>
                        <Button type="primary" ghost onClick={() => {
                            setOpen(true);
                            setDictCode(undefined);
                            setTitle("新增用户")
                        }} style={{ margin: 10 }}>
                            新增
                        </Button>
                    </div>
                    <Table<DataType> scroll={{x:'max-content'}} columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange: handleTableChange
                    }} />
                </Col>
            </Row>
            {open && <EditDictData title={title} open={open} dictType={queryParams.dictType} dictCode={dictCode} OnCanCle={() => {
                setOpen(false);
                getList();
            }} />}
        </div>
    )
};
export default DictView;
